package com.itheima.Servlet;

import com.itheima.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/stu/findAllStudent")
public class findAllStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查看之前先进行校验
        Object username = req.getSession().getAttribute("username");


            resp.getWriter().write("欢迎" + username + "同学");

            //创建字符输入流对象
            String realPath = req.getServletContext().getRealPath("stu.txt");

            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "UTF-8"));
            //创建集合
            ArrayList<Student> list = new ArrayList<>();
            //1.循环读取文件中的学生信息
            String line;
            while ((line = br.readLine()) != null) {
                //2.把学生信息封装成学生对象
                Student stu = new Student();
                String[] split = line.split(",");
                stu.setSid(split[0]);
                stu.setUsername(split[1]);
                stu.setAge(Integer.parseInt(split[2]));
                stu.setScore(Integer.parseInt(split[3]));
                //3.把得到的每个学生信息添加到集合当中
                list.add(stu);
            }
            //把学生信息添加到session当中
            req.getSession().setAttribute("stuList", list);
            //重定向到list.jsp
            resp.sendRedirect(req.getContextPath() + "/list.jsp");



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    }
}
